package com.bak.tt.controller;

import com.alibaba.fastjson.JSON;
import com.bak.tt.dto.TransferReqDTO;
import com.bak.tt.service.TransferService;
import com.bak.tt.service.impl.TransferServiceImpl;
import com.bak.tt.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by yingsy on 2021-01-26.
 */
@WebServlet(name = "transferServlet", urlPatterns = "/transferServlet")
@Slf4j
public class TransferServlet extends HttpServlet {

    private TransferService transferService = new TransferServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String money = req.getParameter("money");
        log.info("请求参数：fromCardNo={}，toCardNo={}，money={}", fromCardNo, toCardNo, money);
        ResultVO resultVO = new ResultVO();

        try {
            TransferReqDTO reqDTO = new TransferReqDTO(fromCardNo, toCardNo, Integer.parseInt(money));
            transferService.transfer(reqDTO);
            resultVO.setCode("200");
        }catch (Exception e){
            resultVO.setCode("201");
            resultVO.setMsg(e.toString());
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JSON.toJSONString(resultVO));
    }
}

